<template>
    <div class="stu-container">
        <div class="stu-btns">
            <el-dialog title="添加学生成绩信息" :visible.sync="dialogFormVisible">
                <el-form :model="form" :rules="rules" ref="addForm">
                    <el-form-item label="学生学号" :label-width="formLabelWidth" prop="sid">
                        <el-input v-model="form.sid"></el-input>
                    </el-form-item>
                    <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
                        <el-input v-model="form.sname" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="所属班级" :label-width="formLabelWidth">
                        <el-select v-model="form.classid" placeholder="请选择">
                            <el-option
                                    v-for="(item,i) in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
                        <el-radio v-model="form.gender" label="男" >男</el-radio>
                        <el-radio v-model="form.gender" label="女" >女</el-radio>
                    </el-form-item>
                    <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
                        <el-input v-model="form.email"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
                        <el-input v-model="form.phone"></el-input>
                    </el-form-item>
                    <el-form-item label="个人简介" :label-width="formLabelWidth" prop="desc">
                        <el-input type="textarea" v-model="form.desc"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="commitForm(1)">确 定</el-button>
                </div>
            </el-dialog>
            <el-dialog title="修改学生成绩信息" :visible.sync="up_dialogFormVisible">
                <el-form :model="form" :rules="rules" ref="addForm">
                    <el-form-item label="学生学号" :label-width="formLabelWidth">
                        <el-input v-model="form.sid" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="stuName">
                        <el-input v-model="form.sname" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="所属班级" :label-width="formLabelWidth" prop="">
                        <el-select v-model="form.classid" placeholder="请选择">
                            <el-option
                                    v-for="(item,i) in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
                        <el-radio v-model="form.gender" label="男" value="0">男</el-radio>
                        <el-radio v-model="form.gender" label="女" value="1">女</el-radio>
                    </el-form-item>
                    <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
                        <el-input v-model="form.email"></el-input>
                    </el-form-item>
                    <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
                        <el-input v-model="form.phone"></el-input>
                    </el-form-item>
                    <el-form-item label="个人简介" :label-width="formLabelWidth" prop="desc">
                        <el-input type="textarea" v-model="form.desc"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="up_dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="commitForm(2)">确 定</el-button>
                </div>
            </el-dialog>

            <el-row>
                <div class="op-row">
                    <div class="btns">
                        <el-button type="success" @click="dialogFormVisible = true">&nbsp&nbsp添加&nbsp&nbsp</el-button>
                        <el-button type="warning" :disabled="up" @click="toUpdate">&nbsp&nbsp修改&nbsp&nbsp</el-button>
                        <el-button type="danger" :disabled="del" @click="toDel">&nbsp&nbsp删除&nbsp&nbsp</el-button>
                    </div>
                    <div class="stu-search">
                        <el-input v-model="search" placeholder="输入关键字搜索"/>
                        <el-select
                                v-model="classed"
                                multiple
                                collapse-tags
                                style="margin-left: 20px;"
                                placeholder="请选择">
                            <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                        <el-button icon="el-icon-search" circle @click="pageQuery"></el-button>
                    </div>
                    <div class="ex-in-port">
                        <el-button type="primary" round @click="importExcel">导入</el-button>
                        <el-button type="primary" round @click="exportExcel">导出</el-button>
                    </div>
                </div>
            </el-row>
        </div>
        <el-table
                max-height="490"
                ref="multipleTable"
                @selection-change="handleSelectionChange"
                tooltip-effect="dark"
                :data="stuList.filter(data => !search || data.sname.toLowerCase().includes(search.toLowerCase()))"
                style="width: 100%"
                :row-class-name="tableRowClassname">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column
                    prop="sid"
                    label="学号"
                    width="150"
                    sortable>
            </el-table-column>
            <el-table-column
                    prop="sname"
                    label="姓名"
                    width="120"
                    sortable>
            </el-table-column>
            <el-table-column
                    prop="gender"
                    label="性别"
                    width="120"
                    sortable>
            </el-table-column>
            <el-table-column
                    prop="classname"
                    label="所属班级"
                    width="150"
                    sortable>
            </el-table-column>
            <el-table-column
                    prop="email"
                    label="邮箱"
            >
            </el-table-column>
            <el-table-column
                    prop="phone"
                    label="手机"
            >
            </el-table-column>
            <el-table-column
                    show-overflow-tooltip
                    prop="desc"
                    label="个人描述">
            </el-table-column>
        </el-table>
        <div class="fen_ye">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total_count">
            </el-pagination>
        </div>
        <PushStudentList @getValueFromStuList="getSonValueStuList" :flag="stu_dialog_flag"
                         :tip="'导入学生列表'"></PushStudentList>
    </div>
</template>
<style>
    .el-table .warning-row {
        background: oldlace;
    }

    .el-table .success-row {
        background: #f0f9eb;
    }
</style>
<style lang="scss" scoped>

    .stu-container {
        .fen_ye {
            text-align: center;
            margin-left: 7px;
            box-shadow: 0 0 9px #999;
        }

        .el-table {
            margin: 5px;
            box-shadow: 0 0 9px #999;
        }

        .stu-btns {
            margin: 0px 5px 5px 5px;
            box-shadow: 0 0 9px #999;
            background-color: #ffffff;
            width: 100%;
            height: 60px;

            .el-form {
                .el-input {
                    width: 260px;
                }
            }

            .op-row {
                padding: 10px;
                display: flex;
                justify-content: space-between;

                .stu-search {
                    .el-input {
                        width: 200px;
                        padding-right: 0px;
                    }

                    .el-select {
                        padding-right: 3px;
                    }
                }

                .ex-in-port {
                    margin-right: 5px;
                }

                .btns {
                    padding-left: 15px;
                }
            }
        }
    }

</style>

<script>
    import PushStudentList from './subcomponents/PushStudentList.vue'
    export default {
        data() {
            var validatePhoto = (rule, value, callback) => {
                if (value !== '' && !(/^1[3456789]\d{9}$/.test(value))) {
                    callback(new Error('手机号格式不正确'));
                } else {
                    callback();
                }
            };
            var validateDisc = (rule, value, callback) => {
                if (value !== '' && value.toString().length > 100) {
                    callback(new Error('个人简介不超过100字'));
                } else {
                    callback();
                }
            };
            var validateEmail = (rule, value, callback) => {
                if (value !== '' && !(/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/).test(value)) {
                    callback(new Error('邮箱格式不正确'));
                } else {
                    callback();
                }
            };
            var validateId = (rule, value, callback) => {
                if (value === '' || !/^[0-9]{6,10}$/.test(value)) {
                    callback(new Error('学号不可为空，仅数字6~10位'));
                } else {
                    callback();
                }
            };
            var validateName = (rule, value, callback) => {
                if (value.toString().length >= 4 || value.toString().length === 0) {
                    callback(new Error('姓名不为空且长度不超过4'));
                } else {
                    callback();
                }
            };
            var validateClass = (rule, value, callback) => {
                if (value === undefined || value.toString() === '') {
                    callback(new Error('班级不能为空'));
                } else {
                    callback();
                }
            };
            var validateGender = (rule, value, callback) => {
                if (value === undefined || value.toString() === '') {
                    callback(new Error('性别不能为空'));
                } else {
                    callback();
                }
            };

            return {
                rules: {
                    email: [
                        {validator: validateEmail, trigger: 'blur'}
                    ],
                    phone: [
                        {validator: validatePhoto, trigger: 'blur'}
                    ],
                    disc: [
                        {validator: validateDisc, trigger: 'blur'}
                    ],
                    sid: [
                        {validator: validateId, trigger: 'blur'}
                    ],
                    sname: [
                        {validator: validateName, trigger: 'blur'}
                    ],
                    stuClass: [
                        {validator: validateClass, trigger: 'blur'}
                    ],
                    gender: [
                        {validator: validateGender, trigger: 'blur'}
                    ],
                },
                total_count:0,
                pageSize:10,
                currentPage: 1,
                up: false,
                del: false,
                stuList: [],
                multipleSelection1: [],
                vle: 0,
                search: '',
                options: [{
                    value: '001',
                    label: 'Java 1 班'
                }, {
                    value: '002',
                    label: 'Java 2 班'
                }],
                classed: [],
                dialogFormVisible: false,
                up_dialogFormVisible: false,
                tempId: '',
                form: {
                    sid: '',
                    sname: '',
                    classid: '1',
                    gender: '',
                    email: '',
                    disc: '',
                    phone:''
                },
                formLabelWidth: '120px',
                stu_dialog_flag: false,
            }
        },
        methods: {
            getSonValueStuList(flag) {
                this.stu_dialog_flag = flag
            },
            importExcel() {
                this.stu_dialog_flag = !this.stu_dialog_flag
            },
            exportExcel() {
                window.location.href = "http://localhost:8080/fanxing/import/batchExport";
            },
            handleSizeChange(val) {
                this.pageSize = val
                this.pageQuery()
                console.log(`每页 ${val} 条`);
            },
            handleCurrentChange(val) {
                this.currentPage = val
                this.pageQuery()
                console.log(`当前页: ${val}`);
            },
            toUpdate() {
                if (this.multipleSelection1.length !== 1) {
                    this.$message({
                        type: 'error',
                        message: '每次只能修改一项哦~'
                    });
                } else {
                    this.form = this.multipleSelection1[0];
                    console.log(this.form)
                    this.up_dialogFormVisible = true
                }
            },
            toDel() {
                if (this.multipleSelection1.length > 0) {
                    this.$confirm('此操作将删除该信息, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        var ids = [];
                        this.multipleSelection1.forEach(item => {
                            ids.push(item.sid)
                        });
                        console.log(ids.join(","))
                        this.$http
                            .get("stu/delStu?ids="+ids.join(","))
                            .then(result => {
                                if (result.body.status === 0) {
                                    this.classed = result.body.message;
                                }
                            });
                        this.pageQuery()
                        this.getStuTotal()
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });

                } else {
                    this.$message({
                        type: 'error',
                        message: '请勾选你需要删除的选项~'
                    });
                }
            },
            commitForm(val) {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.options.some(item => {
                            if (item.value === this.form.classid) {
                                console.log(item);
                                console.log(this.form.classid);
                            }
                        })
                        if (val === 1) {//添加
                            this.dialogFormVisible = false
                            this.stuList.unshift(this.form)

                            this.$http.post("http://localhost:8080/stu/insertone?sid="+this.form.sid+"&sname="+this.form.sname+"&classid="+this.form.classid
                            +"&gender="+this.form.gender+"&email="+this.form.email+"&phone="+this.form.phone)
                                .then(function(data){

                                console.log(data)

                            }).catch(function(){
                                console.log("服务器异常！");
                            });

                            this.$message({
                                type: 'success',
                                message: '添加成功'
                            });
                            this.getStuTotal()
                            this.pageQuery()
                        } else {//修改
                            this.up_dialogFormVisible = false

                            this.$http.post("http://localhost:8080/stu/update?sid="+this.form.sid+"&sname="+this.form.sname+"&classid="+this.form.classid
                                +"&gender="+this.form.gender+"&email="+this.form.email)
                                .then(function(data){
                                    this.$message({
                                        type: 'success',
                                        message: '修改成功'
                                    });
                                    console.log(data)
                                }).catch(function(){
                                console.log("服务器异常！");
                            });
                        }
                    } else {
                        return false
                    }
                });
            },
            getManagedClass() {
                this.$http
                    .get("teach/getManagedClass")
                    .then(result => {
                        if (result.body.status === 0) {
                            this.classed = result.body.message;
                        }
                    });
            },
            tableRowClassname({row, rowIndex}) {
                if (rowIndex % 2 === 1) {
                    return 'warning-row';
                } else if (rowIndex % 2 === 0) {
                    return 'success-row';
                }
                return '';
            },
            handleSelectionChange(val) {
                this.multipleSelection1 = val;
            },
            pageQuery(){
                var idArr = [];
                this.classed.forEach(item => {
                    idArr.push(item)
                })
                this.$http
                    .get("http://localhost:8080/stu/pageQuery?sname="+this.search+"&cid="+idArr.join(",")+"&cur="+this.currentPage+"&size="+this.pageSize)
                    .then(result => {
                        console.log(result)
                        if (result.status === 200) {
                            this.stuList = result.body
                        }else{
                            console.log("NO")
                        }
                    });
            },
            getStuTotal(){
                this.$http
                    .get("stu/getStuTotal")
                    .then(result => {
                        this.total_count = result.body
                    });
            }
        },
        created() {
            this.getStuTotal()

            this.pageQuery()

            // this.getManagedClass()
        },
        watch: {
            dialogFormVisible: function (newVal, oldVal) {
                // console.log("newVal:" + newVal + "   oldVal:" + oldVal)
                if (!newVal) {
                    // console.log("修改")
                    this.form = {

                    }
                }
            }, up_dialogFormVisible: function (newV, oldV) {
                if (!newV) {
                    this.form = {

                    }
                }
            }
        },
        components: {
            PushStudentList
        }
    }
</script>

